package com.yicong.ants.ui.circle.article;

import android.graphics.Rect;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.cchao.simplelib.Const;
import com.cchao.simplelib.core.CollectionHelper;
import com.cchao.simplelib.core.Router;
import com.cchao.simplelib.core.RxBus;
import com.cchao.simplelib.core.RxHelper;
import com.cchao.simplelib.core.UiHelper;
import com.cchao.simplelib.ui.adapter.StatefulBindMultiQuickAdapter;
import com.cchao.simplelib.ui.fragment.BaseStatefulFragment;
import com.cchao.simplelib.util.StringHelper;
import com.kennyc.view.MultiStateView;
import com.yicong.ants.BR;
import com.yicong.ants.Constants;
import com.yicong.ants.R;
import com.yicong.ants.bean.circle.ArticleItem;
import com.yicong.ants.bean.circle.OfficeItemWrapper;
import com.yicong.ants.databinding.CommonRecylerBinding;
import com.yicong.ants.manager.AppHelper;
import com.yicong.ants.manager.BusinessHelper;
import com.yicong.ants.manager.ImageHelper;
import com.yicong.ants.manager.UserManager;
import com.yicong.ants.manager.http.RetrofitHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.jzvd.Jzvd;


/**
 * 蚁丛课堂页面
 *
 * @author cchao
 * @version 2020-11-3 16:23:55
 */
public class ArticleListFragment extends BaseStatefulFragment<CommonRecylerBinding> {

    StatefulBindMultiQuickAdapter<OfficeItemWrapper> mAdapter;
    String mChannel;

    @Override
    protected int getLayoutId() {
        return R.layout.common_recyler;
    }

    @Override
    protected void initEventAndData() {
        initAdapter();
        onLoadData();
        mDataBind.swipeRefresh.setBackgroundColor(UiHelper.getColor(R.color.white));
        mDataBind.swipeRefresh.setOnRefreshListener(() -> {
            onLoadData();
            RxHelper.timerConsumer(8000, aLong -> mDataBind.swipeRefresh.setRefreshing(false));
        });

        RxBus.get().toObservable(commonEvent -> {
            switch (commonEvent.getCode()) {
                case Constants.Event.Main_Tab_Checked:
                    if (!"1".equalsIgnoreCase(String.valueOf(AppHelper.mCurMainTabIndex))) {
                        onPause();
                    }
                    break;
            }
        });
    }

    public static ArticleListFragment get(String channel) {
        ArticleListFragment fragment = new ArticleListFragment();
        fragment.mChannel = channel;
        return fragment;
    }

    private void initAdapter() {
        mDataBind.recycler.setLayoutManager(new LinearLayoutManager(mContext));
        mAdapter = new StatefulBindMultiQuickAdapter<OfficeItemWrapper>(null) {

            @Override
            public Map<Integer, Integer> getTypeLayoutMap() {
                Map<Integer, Integer> map = new HashMap<>(8);
                map.put(1, R.layout.office_item_type1);
                map.put(10, R.layout.office_item_type10);
                return map;
            }

            @Override
            protected void convert(DataBindViewHolder helper, OfficeItemWrapper data) {
                switch (helper.getItemViewType()) {
                    case 1: // 单图
                        convertType1(helper, (ArticleItem) data.getObject());
                        break;
                    case 10: // 无图，三图，视频
                        convertType10(helper, (ArticleItem) data.getObject());
                        break;
                }
            }

            private void convertType1(DataBindViewHolder helper, ArticleItem item) {
                helper.getBinding().setVariable(BR.bean, item);
                int width = (int) (UiHelper.getScreenWidth() / 4f);
                int height = (int) (width * 1.0f / 110 * 83f);
                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(width, height);
                View rootView = helper.getBinding().getRoot();
                rootView.findViewById(R.id.image_1).setLayoutParams(layoutParams);
                if (CollectionHelper.isEmpty(item.getUrls_files())) {
                    return;
                }
                ImageHelper.loadImageRound(rootView.findViewById(R.id.image_1), item.getUrls_files().get(0), 4);
                setItemClick(helper.getBinding().getRoot(), item);
            }

            private void convertType10(DataBindViewHolder helper, ArticleItem item) {
                helper.getBinding().setVariable(BR.bean, item);
                View rootView = helper.getBinding().getRoot();
                setItemClick(helper.getBinding().getRoot(), item);

                ViewGroup imageContainer = rootView.findViewById(R.id.image_container);
                ViewGroup videoContainer = rootView.findViewById(R.id.video_container);

                UiHelper.setVisibleElseGone(imageContainer, false);
                UiHelper.setVisibleElseGone(videoContainer, false);

                if (CollectionHelper.isEmpty(item.getUrls_files()) || item.getType() == 0) {
                    return;
                }
                // 类型:0=无图;1=1图;2=3图;3=视频
                if (item.getType() == 2) {
                    int width = (int) ((UiHelper.getScreenWidth() - UiHelper.dp2px(48)) / 3f);
                    int height = (int) (width * 1.0f / 110 * 83);
                    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(width, height);
                    ImageView imageView1 = rootView.findViewById(R.id.image_1);
                    ImageView imageView2 = rootView.findViewById(R.id.image_2);
                    ImageView imageView3 = rootView.findViewById(R.id.image_3);
                    imageView1.setLayoutParams(layoutParams);
                    imageView2.setLayoutParams(layoutParams);
                    imageView3.setLayoutParams(layoutParams);

                    UiHelper.setVisibleElseGone(imageView2,false);
                    UiHelper.setVisibleElseGone(imageView3,false);

                    ImageHelper.loadImageRound(imageView1, item.getUrls_files().get(0), 4);
                    if (item.getUrls_files().size() > 1) {
                        ImageHelper.loadImageRound(imageView2, item.getUrls_files().get(1), 4);
                        UiHelper.setVisibleElseGone(imageView2,true);
                    }
                    if (item.getUrls_files().size() > 2) {
                        ImageHelper.loadImageRound(imageView3, item.getUrls_files().get(2), 4);
                        UiHelper.setVisibleElseGone(imageView3,true);
                    }
                    UiHelper.setVisibleElseGone(imageContainer, true);
                    return;
                }
                if (item.getType() == 3) {
                    ImageHelper.loadImageRound(rootView.findViewById(R.id.video_cover), item.getVideoFrame(), 4, R.drawable.common_place_holder_pure);
                    UiHelper.setVisibleElseGone(videoContainer, true);
                }
            }

            void setItemClick(View view, ArticleItem item) {
                View.OnClickListener onClickListener = v -> {
                    switch (v.getId()) {
                        case R.id.like:
                            //
                            if (UserManager.notLogin()) {
                                showToast("请先登录");
                                return;
                            }
                            showProgress();
                            Map<String, String> map = new HashMap<>();
                            map.put("office_id", item.getId());
                            addSubscribe(RetrofitHelper.getApis().circleLike(map)
                                .compose(RxHelper.toMain())
                                .subscribe(respBean -> {
                                    hideProgress();
                                    if (respBean.isCodeFail()) {
                                        showToast(respBean.getMsg());
                                        return;
                                    }
                                    item.setIs_like(Math.abs(item.getIs_like() - 1));
                                    if (item.getIs_like() == 1) {
                                        item.setLike_qty(String.valueOf(Integer.parseInt(item.getLike_qty()) + 1));
                                    } else {
                                        item.setLike_qty(String.valueOf(Integer.parseInt(item.getLike_qty()) - 1));
                                    }
                                    item.update_text(view.findViewById(R.id.like));
                                }, RxHelper.getHideProgressConsumer(ArticleListFragment.this)));
                            break;
                        case R.id.share:
                            //
                            String image = "";
                            if (CollectionHelper.isNotEmpty(item.getUrls_files())) {
                                image = item.getUrls_files().get(0);
                            }
                            BusinessHelper.shareWx(getActivity()
                                , "蚁丛社区文章"
                                , item.getTitle()
                                , image
                                , item.getLink(), () -> {
                                    Map<String, String> map2 = new HashMap<>();
                                    map2.put("office_id", item.getId());
                                    addSubscribe(RetrofitHelper.getApis().shareCount(map2)
                                        .compose(RxHelper.toMain())
                                        .subscribe(respBean -> {
                                        }, RxHelper.getHideProgressConsumer(ArticleListFragment.this)));
                                });
                            break;
                    }
                };
                if (view.findViewById(R.id.like) != null) {
                    item.update_text(view.findViewById(R.id.like));
                    view.findViewById(R.id.like).setOnClickListener(onClickListener);
                }

                if (view.findViewById(R.id.share) != null) {
                    view.findViewById(R.id.share).setOnClickListener(onClickListener);
                }
            }

            @Override
            public void loadPageData(int page) {
                loadPage(page);
            }

        };
        mAdapter.bindToRecyclerView(mDataBind.recycler);
        mAdapter.setOnItemClickListener((adapter, view, position) -> {
            OfficeItemWrapper itemWrapper = mAdapter.getData().get(position);
            ArticleItem officeItem = (ArticleItem) itemWrapper.getObject();
            if (StringHelper.isNotEmpty(officeItem.getLink())) {
                Router.turnTo(mContext, ArticleWebActivity.class)
                    .putExtra(Constants.Extra.Id, officeItem.getId())
                    .putExtra(Const.Extra.Web_View_Url, officeItem.getLink())
                    .putExtra(Const.Extra.Web_View_Tile, "蚁丛社区文章")
                    .start();
            }
        });
        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(mContext, DividerItemDecoration.VERTICAL) {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                int adapterPosition = parent.getChildAdapterPosition(view);
                outRect.bottom = UiHelper.dp2px(14);
                outRect.top = UiHelper.dp2px(10);
                if (adapterPosition == 0) {
                    outRect.top = UiHelper.dp2px(8);
                }
            }
        };

        dividerItemDecoration.setDrawable(UiHelper.getDrawable(R.drawable.recycler_divider_eee));
        mDataBind.recycler.addItemDecoration(dividerItemDecoration);
    }

    @Override
    protected void onLoadData() {
        loadPage(1);
    }

    void loadPage(final int page) {
        final Map<String, String> params = new HashMap<>();
        params.put("page", String.valueOf(page));
        if (StringHelper.isNotEmpty(mChannel)) {
            params.put("channel", mChannel);
        }

        if (page == 1) {
            mAdapter.setViewState(MultiStateView.VIEW_STATE_LOADING);
        }

        addSubscribe(RetrofitHelper.getApis().circleIndex(params)
            .compose(RxHelper.toMain())
            .subscribe(respBean -> {
                if (respBean.isCodeFail()) {
                    showToast(respBean.getMsg());
                    mAdapter.loadMoreComplete();
                }
                mDataBind.swipeRefresh.setRefreshing(false);
                // 包装数据
                List<ArticleItem> data = respBean.getList();
                List<OfficeItemWrapper> list = new ArrayList<>();
                for (ArticleItem datum : data) {
                    if (datum.getType() == 1) {
                        list.add(OfficeItemWrapper.of(1, datum));
                    } else {
                        list.add(OfficeItemWrapper.of(10, datum));
                    }
                }
                mAdapter.solvePagesData(list, page, Constants.PAGE_SIZE);
            }, RxHelper.getSwitchableErrorConsumer(mAdapter)));
    }

    @Override
    public void onPause() {
        super.onPause();
        Jzvd.releaseAllVideos();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            //相当于Fragment的onResume
        } else {
            //相当于Fragment的onPause
            onPause();
        }
    }
}
